package com.demo6.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Map;

@Controller
@RequestMapping("/updown")
public class updowncontroller {
    //文件上传页面
    @RequestMapping("/uppage")
    public String uppage(){
        return "Upfile";
    }
    //文件上传操作
    @RequestMapping("/upload")
    //@ResponseBody
    public String upload(Map<String, Object> map, @RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "请选择文件";
        }
        //设置文件上传的目录
        File path=new File("src/main/resources/static/images");
        //判断该路径是否存在
        if(!path.exists()){
            //该路径不存在
            path.mkdirs();
        }
        //获取文件名
        String filename=file.getOriginalFilename();
        //将文件名放到map中 再送到页面
        map.put("pic",filename);
        //创建保存文件的绝对路径
        File filepath=new File(path.getAbsolutePath()+"/"+filename);
        //保存文件
        file.transferTo(filepath);
        return "Upfile";
    }
    @Autowired
    //ResourceLoader资源加载
    private ResourceLoader loader;
    //加载图片Response响应Entity实体
    @RequestMapping("/showpic")
    public ResponseEntity showpic(@RequestParam("picname") String picname){
        return ResponseEntity.ok(loader.getResource("file:src/main/resources/static/images/"+picname));
    }
    //下载文件的页面
    @RequestMapping("/downpage")
    public String downpage(){
        return "downfile";
    }
    //文件下载操作
    @RequestMapping("/download")
    @ResponseBody
    public String download(@RequestParam("fname") String fname, HttpServletResponse response) throws IOException {
        //获取下载的文件
        File file=new File("src/main/resources/static/images/"+fname);
        //设置下载文件的方式 Content内容 Disposition设置 attachment附件
        response.setHeader("Content-Disposition","attachment;filename="+fname);
        //下载
        IOUtils.copy(new FileInputStream(file),response.getOutputStream());
        return "下载成功";
    }
}
